// fabu.js
const { chooseMedia, uploadFile, postProduct } = require("../../utils/Requestutil");
Page({
  data: {
    fileList: [],
    imageList: '',
    videoUrl: '',
    title: '',
    description: '',
    priceInputValue: '', // 价格输入值
    shippingFee: '', // 快递费输入值
    shippingMethod: '包邮', // 发货方式，默认为'free'（包邮）
    showPriceInput: false, // 是否显示价格输入区域
    showShippingInput: false, // 是否显示发货方式输入区域
    isKeyboardShow: false, // 是否显示键盘
    price: '', // 存储最终的价格,
    userId: ''
  },
  onLoad(){
    const userId = wx.getStorageSync('userId');
    console.log(userId);
    // 检查用户的ID是否存在，不存在就跳转登录
    if(!userId){
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }else{
      this.setData({
        userId: userId
      })
    }
  },

  inputChange(e) {
    const { value } = e.detail;
    const filedType = e.currentTarget.dataset.type;
    this.setData({
      [filedType]: value // 动态更新对应的字段
    });
  },

  onPriceInput(e) {
    this.setData({
      priceInputValue: e.detail.value
    });
  },

  onShippingFeeInput(e) {
    this.setData({
      shippingFee: e.detail.value
    });
  },

  onKeyTap(e) {
    const key = e.currentTarget.dataset.key;
    let data = {};
    if (key === 'delete') {
      data[this.data.currentInputField] = this.data[this.data.currentInputField].slice(0, -1);
    } else if (key === 'confirm') {
      // 如果当前输入价格，确认后隐藏键盘和价格输入部分
      if (this.data.currentInputField === 'priceInputValue') {
        data.isKeyboardShow = false;
        data.showPriceInput = false;
        this.setData({
          price: this.data.priceInputValue // 保存价格
        });
      } else if (this.data.currentInputField === 'shippingFee') {
        data.isKeyboardShow = false;
        data.showShippingInput = false;
        this.setData({
          shippingFee: this.data.shippingFee // 保存快递费
        });
      }
    } else {
      data[this.data.currentInputField] = this.data[this.data.currentInputField] + key;
    }
    this.setData(data);
  },

  onShippingMethodChange(e) {
    const shippingMethod = e.detail.value;
    let data = {
      shippingMethod,
      showShippingInput: false, // 默认不显示
      isKeyboardShow: false, // 默认不显示键盘
    };
    if (shippingMethod === 'own') {
      data.showShippingInput = true;
      data.isKeyboardShow = true;
      data.currentInputField = 'shippingFee';
    } else {
      data.shippingFee = ''; // 切换发货方式时重置快递费
    }
    this.setData(data);
  },

  toggleSection(e) {
    const type = e.currentTarget.dataset.type;
    let data = {
      showPriceInput: false,
      showShippingInput: false,
      isKeyboardShow: false,
    };
    if (type === 'price') {
      data.showPriceInput = true;
      data.currentInputField = 'priceInputValue';
      data.isKeyboardShow = true;
    } else if (type === 'shipping') {
      data.showShippingInput = true;
      data.currentInputField = 'shippingMethod';
      if (this.data.shippingMethod === 'own') {
        data.currentInputField = 'shippingFee';
        data.isKeyboardShow = true;
      }
    }
    this.setData(data);
  },

  chooseImage() {
    chooseMedia()
      .then((files) => {
        let imageList = [...this.data.imageList];  // 用于存储上传成功的图片 URL
        let videoUrl = this.data.videoUrl;
        
        // 限制图片最多选择9张，视频只能选择一个
        let imageFiles = files.filter(file => file.fileType === 'image');
        let videoFiles = files.filter(file => file.fileType === 'video');
  
        if (imageList.length + imageFiles.length > 9) {
          wx.showToast({
            title: '最多只能选择9张图片',
            icon: 'none',
          });
          return;
        }
        
        if (videoFiles.length > 0 && !videoUrl) {
          videoUrl = videoFiles[0].tempFilePath;  // 视频文件（仅限一个）
        }
        
        // 上传图片和视频
        this.uploadMediaFiles(imageFiles.map(file => file.tempFilePath), videoUrl);
      })
      .catch((error) => {
        console.error('选择文件失败:', error);
      });
  },
  
  async uploadMediaFiles(imagePaths, videoPath) {
    console.log('开始上传图片和视频');
    
    let uploadedImageUrls = [];  // 用于存储成功上传的图片 URL 列表
    let uploadedVideoUrl = this.data.videoUrl || '';  
  
    // 上传图片
    for (let i = 0; i < imagePaths.length; i++) {
      try {
        let res = await uploadFile(imagePaths[i], 'image');
        console.log('上传图片结果:', res);
        if (res.code === 200) {
          uploadedImageUrls.push(res.data.imageUrl);  // 添加成功上传的图片 URL
        }
      } catch (error) {
        console.error('图片上传失败:', error);
      }
    }
  
    // 上传视频
    if (videoPath && !uploadedVideoUrl) {
      try {
        let res = await uploadFile(videoPath, 'video');
        console.log('上传视频结果:', res);
        if (res.code === 200) {
          uploadedVideoUrl = res.data.videoUrl;  // 设置上传成功的视频 URL
        }
      } catch (error) {
        console.error('视频上传失败:', error);
      }
    }
    // 扁平化数组，避免嵌套
    uploadedImageUrls = uploadedImageUrls.flat();
    // 更新页面数据
    this.setData({
      imageList: [...this.data.imageList, ...uploadedImageUrls],  
      videoUrl: uploadedVideoUrl,    // 更新为成功上传的视频 URL
    });
  },

  publishProduct: async function(){
    // 通过正则表达式判断该商品属于哪个类别
    const categories = [
      {id: 1,  regex: /(衣服|服装|穿搭|时尚|外套|衬衫|裙子|裤子|T恤|运动服|羽绒服|连衣裙|夹克|毛衣)/, name: '衣服穿搭' },
      { id: 2, regex: /(宿舍|寝室|家居|生活用品|床单|枕头|台灯|电风扇|收纳|书桌|衣柜|垃圾桶|拖把|暖气)/, name: '宿舍用品' },
      { id: 3, regex: /(书|教材|笔记|二手书籍|小说|漫画|工具书|课本|参考书|自习资料|教辅)/, name: '二手书籍' },
      { id: 4, regex: /./, name: '其他' },  // 默认匹配其他，确保没有遗漏
    ];
    // 设置类别的默认值
    let category = 4;
    // 根据title和description来识别商品属于哪个类别
    for (const cat of categories) {
      if(cat.regex.test(this.data.title) || cat.regex.test(this.data.description)){
        category = cat.id;
        break;
      }
    }
    const productData = {
      title: this.data.title,
      description: this.data.description,
      salePrice: parseFloat(this.data.priceInputValue),
      user: { id: this.data.userId },
      freeShopping: this.data.shippingMethod === '包邮' ? 0 : 1,
      category: category,
    };
    // 仅在 imageList 存在并有内容时才添加 imageUrl
    if (this.data.imageList && this.data.imageList.length > 0) {
      productData.imageUrl = JSON.stringify(this.data.imageList);
    }
    // 仅在 videoUrl 存在时才添加 videoUrl
    if (this.data.videoUrl) {
      productData.videoUrl = this.data.videoUrl;
    }
    try{
      const res = await postProduct({
        url: '/product/save',
        data: productData,
        method: 'POST',
        header: {
          "content-type": "application/json"
        }
      });
      if(res.code === 0){
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
      }else{
        wx.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        });
      }
    }catch(err){
      wx.showToast({
        title: '发布出错，请检查网络',
        icon: 'none'
      })
    };
    console.log("User ID:", this.data.userId);
    console.log("Product Data:", productData);
  }
});